<!--
 * @Author: quit
 * @Date: 2021-12-08 10:37:09
 * @LastEditTime: 2021-12-15 17:41:09
 * @Descripttion: 阈值配置
-->
<template>
  <div id="SubModeManager">
    <div class="app-container" style="height: 100%">
      <el-row :gutter="5">
        <!-- 左侧 -->
        <el-col :span="4" class="left">
          <el-card>
            <div v-loading="treeLoading" class="item-box">
              <el-tree ref="tree" :data="treeData" :props="defaultProps" @node-click="handleNodeClick" />
            </div>
          </el-card>
        </el-col>
        <!-- 右侧 -->
        <el-col :span="20" class="right">
          <el-card>
            <el-row class="right-container">
              <el-col>
                <el-divider content-position="left">搜索信息</el-divider>
                <div class="search">
                  <el-form :inline="true" :model="searchFrom" class="demo-form-inline">
                    <el-form-item :label="'阈值名称'">
                      <el-input v-model="searchFrom.thresholdname" disabled :placeholder="'请选择阈值名称'" />
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" icon="el-icon-refresh-right" @click="refresh">{{ '重置' }}</el-button>
                    </el-form-item>
                  </el-form>
                </div>
              </el-col>
              <el-col class="btns">
                <el-button type="primary" size="mini" icon="el-icon-circle-plus-outline" @click="addItemsBtn">{{ '添加阈值配置' }}</el-button>
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="batchRemove">{{ $t('button.batchRemove') }}</el-button>
              </el-col>
              <el-col>
                <el-table
                  ref="table"
                  v-loading="loading"
                  :max-height="maxHeight"
                  :data="tableData"
                  :empty-text="$t('table.emptyText')"
                  style="width: 100%"
                  @selection-change="handleSelectionChange"
                >
                  <el-table-column type="selection" min-width="40" fixed="left" />
                  <el-table-column prop="id" label="ID" min-width="70" fixed="left" />
                  <el-table-column prop="thresholdid" :label="'阈值ID'" min-width="70" fixed="left" />
                  <el-table-column :label="'阈值名'" min-width="160">
                    <template slot-scope="scope">
                      <div>
                        {{
                          treeData &&
                            treeData.find(item => {
                              return item.thresholdid === scope.row.thresholdid
                            }).thresholdname
                        }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="mini" :label="'最小值'" min-width="60" />
                  <el-table-column prop="max" :label="'最大值'" min-width="60" />
                  <el-table-column prop="andor" header-align="center" align="center" :label="'与或'" min-width="70">
                    <template slot-scope="scope">
                      <span v-if="scope.row.andor === 0" class="andor-text">条件或</span>
                      <span v-if="scope.row.andor === 1" class="andor-text">条件与</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="thresholdtext" :label="'文字描述'" min-width="200" />
                  <el-table-column prop="thresholdcss" :label="'文字样式'" min-width="295" />
                  <el-table-column header-align="center" align="center" fixed="right" :label="$t('table.operable')" min-width="150">
                    <template slot-scope="scope">
                      <el-button type="warning" size="mini" @click="handleEdit(scope.row)">{{ $t('button.edit') }}</el-button>
                      <el-button type="danger" size="mini" @click="handleDetele(scope.row)">{{ $t('button.delete') }}</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <!-- 分页 -->
                <el-pagination
                  :current-page="pages.page"
                  :page-sizes="[1, 5, 10, 15]"
                  :page-size="pages.size"
                  layout="prev, pager, next, total, sizes, jumper"
                  :total="pages.total"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                />
              </el-col>
            </el-row>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <!-- 添加\修改弹出层 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="40%" @close="addDialogClose">
      <el-form ref="dialogFrom" :model="dialogFrom" label-width="100px" class="dialog-from">
        <el-form-item label="最大值">
          <el-input v-model="dialogFrom.max" placeholder="请输入最大值" />
        </el-form-item>
        <el-form-item label="最小值">
          <el-input v-model="dialogFrom.mini" placeholder="请输入最小值" />
        </el-form-item>
        <el-form-item label="与或">
          <el-select v-model="dialogFrom.andor" clearable filterable placeholder="请选择条件">
            <el-option v-for="(item, index) in andorData" :key="index" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="文字描述">
          <el-input v-model="dialogFrom.thresholdtext" type="textarea" :rows="2" placeholder="请输入项目描述" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="文字颜色">
              <el-color-picker v-model="color1" />
              <div class="color-data">{{ color1 }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="背景颜色">
              <el-color-picker v-model="color2" />
              <div class="color-data">{{ color2 }}</div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-input v-model="thresholdcss" disabled />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button v-if="addDialogState === 0" type="primary" @click="sendAddItem">确 定</el-button>
        <el-button v-if="addDialogState === 1" type="primary" @click="sendEditItem">提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import $ from 'jquery'
import { getThresholdList, getThresholdsConfigList, addThresholdsConfigItem, editThresholdsConfigItem, deleteThresholdsConfigItem } from '@/api/BmRequest'

export default {
  components: {},
  data() {
    return {
      treeData: [],
      treeLoading: false,
      defaultProps: { children: 'children', label: 'thresholdname' },
      searchFrom: { thresholdname: null, thresholdid: null },
      maxHeight: null,
      loading: false,
      isCheckedArr: [],
      tableData: [],
      pages: { page: 1, size: 10, total: 0 },
      dialogTitle: '',
      addDialogState: null,
      dialogVisible: false,
      dialogFrom: {
        id: null,
        thresholdid: null,
        mini: null,
        max: null,
        andor: null,
        thresholdtext: null
      },
      color1: '#ffffff',
      color2: '#409eff',
      andorData: [
        { label: '条件或(or)', value: 0 },
        { label: '条件与(and)', value: 1 }
      ]
    }
  },
  // 监听属性 类似于data概念
  computed: {
    thresholdcss() {
      return `{ "color": "${this.color1}", "backcolor": "${this.color2}" }`
    }
  },
  // 监控data中的数据变化
  watch: {},
  created() {
    this.geTreeData()
    this.getThresholdsConfigList()
  }, // 生命周期 - 创建完成（可以访问当前this实例）
  mounted() {
    this.setTableHeight()
    window.onresize = () => {
      this.setTableHeight()
    }
  }, // 生命周期 - 挂载完成（可以访问DOM元素）
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {}, // 如果页面有keep-alive缓存功能，这个函数会触发
  // 方法集合
  methods: {
    // 动态设置表格高
    setTableHeight() {
      let num = $('.right-container').height() - 203
      this.maxHeight = num
    },
    /* 左侧树形数据操作 */
    // 获取类型列表
    async geTreeData() {
      this.treeLoading = true
      try {
        const { data } = await getThresholdList()
        this.treeData = data
      } catch (error) {
        console.log(error)
      } finally {
        this.treeLoading = false
      }
    },
    // 节点点击事件
    handleNodeClick(data) {
      this.searchFrom.thresholdname = data.thresholdname
      this.searchFrom.thresholdid = data.thresholdid
      this.getThresholdsConfigList()
    },

    /* 右侧列表操作 */
    // 获取阈值配置数据列表
    async getThresholdsConfigList() {
      const obj = {
        thresholdinfo: { thresholdid: this.searchFrom.thresholdid },
        pages: { page: this.pages.page, size: this.pages.size }
      }
      try {
        this.loading = true
        const { data } = await getThresholdsConfigList(obj)
        this.tableData = data.records
        this.pages.page = data.current
        this.pages.size = data.size
        this.pages.total = data.total
      } catch (error) {
        console.log(error)
      } finally {
        this.loading = false
      }
    },

    // 重置按钮
    refresh() {
      this.searchFrom.thresholdname = null
      this.searchFrom.thresholdid = null
      this.getThresholdsConfigList()
    },

    // 添加按钮
    addItemsBtn() {
      if (!this.searchFrom.thresholdname) {
        this.$message.warning('请先选着需要添加的类型!')
      } else {
        this.addDialogState = 0
        this.dialogTitle = '添加阈值配置信息'
        this.dialogVisible = true
      }
    },

    /* table选择事件 */
    handleSelectionChange(val) {
      let nowArr = []
      val.forEach(item => {
        nowArr.push(item.id)
      })
      this.isCheckedArr = nowArr
    },

    // 批量删除
    async batchRemove() {
      if (this.isCheckedArr.length > 0) {
        this.$confirm('此操作将删除所选项目, 是否继续?', '确认操作', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async() => {
            if (this.isCheckedArr.length === this.tableData.length) {
              if (this.pages.page > 1) {
                this.pages.page--
              } else {
                this.pages.page = 1
              }
            }
            const { message } = await deleteThresholdsConfigItem(this.isCheckedArr)
            await this.getThresholdsConfigList()
            this.$message.success({ message })
          })
          .catch(error => {
            console.log(error)
            this.$refs.table.clearSelection()
          })
      } else {
        this.$message.warning('请选择需要删除的项目')
      }
    },

    /* 弹出框事件 */
    // 关闭
    addDialogClose() {
      this.dialogFrom = { id: null, thresholdid: null, mini: null, max: null, andor: null, thresholdtext: null }
      this.dialogTitle = null
      this.addDialogState = null
      this.color1 = '#ffffff'
      this.color2 = '#409eff'
    },
    // 确定
    async sendAddItem() {
      const obj = {
        thresholdid: this.searchFrom.thresholdid,
        mini: this.dialogFrom.mini,
        max: this.dialogFrom.max,
        andor: this.dialogFrom.andor,
        thresholdtext: this.dialogFrom.thresholdtext,
        thresholdcss: this.thresholdcss
      }
      try {
        const { message } = await addThresholdsConfigItem(obj)
        this.$message.success(message)
      } catch (error) {
        console.log(error)
      } finally {
        if (this.tableData.length === this.pages.size) {
          this.pages.page++
        }
        this.getThresholdsConfigList()
        this.dialogVisible = false
      }
    },
    // 提交
    async sendEditItem() {
      const obj = {
        id: this.dialogFrom.id,
        thresholdid: this.searchFrom.thresholdid,
        mini: this.dialogFrom.mini,
        max: this.dialogFrom.max,
        andor: this.dialogFrom.andor,
        thresholdtext: this.dialogFrom.thresholdtext,
        thresholdcss: this.thresholdcss
      }
      try {
        const { message } = await editThresholdsConfigItem(obj)
        this.$message.success(message)
      } catch (error) {
        console.log(error)
      } finally {
        this.dialogVisible = false
        this.getThresholdsConfigList()
      }
    },

    /* tabel-item 操作 */
    // 编辑
    handleEdit(data) {
      if (data.thresholdcss) {
        const color = JSON.parse(data.thresholdcss)
        this.color1 = color.color
        this.color2 = color.backcolor
      }
      this.dialogFrom = { ...data }
      this.addDialogState = 1
      this.dialogTitle = '编辑阈值配置信息'
      this.dialogVisible = true
    },
    // 删除
    handleDetele(data) {
      this.$confirm('此操作将删除当前项目, 是否继续?', '确认操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const nowArr = [data.id]
          const { message } = await deleteThresholdsConfigItem(nowArr)
          if (this.tableData.length === 1) {
            if (this.pages.page > 1) {
              this.pages.page--
            } else {
              this.pages.page = 1
            }
          }
          await this.getThresholdsConfigList()
          this.$message.success({ message })
        })
        .catch(error => {
          console.log(error)
        })
    },

    /* 分页操作 */
    // 分页当前页切换
    async handleCurrentChange(newPage) {
      this.pages.page = newPage
      await this.getThresholdsConfigList()
    },
    // 分页显示条数切换
    async handleSizeChange(newSize) {
      this.pages.size = newSize
      await this.getThresholdsConfigList()
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__body {
  padding: 15px 20px;
}
::v-deep .el-divider {
  margin: 14px 0 !important;
}

.andor-text {
  color: blue;
}

#SubModeManager {
  .app-container {
    .left {
      .item-box {
        height: calc(100vh - 92px);
        overflow: auto;
        .tree-search {
          margin-bottom: 10px;
        }
      }
    }
    .right {
      .right-container {
        height: calc(100vh - 92px);
        .search {
          border: 1px solid #dcdfe6;
          border-top: none;
          padding: 34px 10px 10px 10px;
          margin-top: -14px;
          .el-input {
            width: 240px;
          }
          .el-button {
            margin-left: 20px;
          }
        }
        .btns {
          padding: 10px 0;
        }
      }
    }
  }
  .dialog-from {
    .el-form-item {
      margin-bottom: 16px;
      position: relative;
    }

    .el-input,
    .el-select,
    .el-textarea {
      width: calc(100% - 10px);
    }

    .color-data {
      display: inline-block;
      position: absolute;
      top: 0;
      height: 40px;
      line-height: 40px;
      padding: 0 0 0 15px;
    }
  }
}
</style>
